import { MciDialog, MciMessageBox, MciNotification } from '@/components/base';
import { postWorkflowApprovalTaskAdd, IPostWorkflowApprovalTaskAddReq } from '@/api';
import { useApprovalProvide } from '@/components/business/Approval/approval-helper';
import { PropType } from 'vue';
import { IOption } from '@/components/base/Select';
import { IVitalFormConfig, IVitalFormCtx, VitalForm } from 'vital';
import * as i18n from '@/locales';
import { useTaskId } from '../../approval-helper/useTaskId';
// 添加加签审批人
export const AddSignUser = defineComponent({
  props: {
    excludeId: {
      type: Array as PropType<number[]>,
      default: () => []
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const formRef = ref(null as TNullable<IVitalFormCtx<IPostWorkflowApprovalTaskAddReq>>);
    const { getApprovalProgress, processInstanceId } = useApprovalProvide();
    const { taskId } = useTaskId();

    const confirmHandle = async () => {
      await formRef.value?.validate();
      const model = formRef.value?.getModel();

      const submitHandle = async () => {
        // 加签
        await postWorkflowApprovalTaskAdd({
          userIds: model?.userIds,
          processInstanceId: processInstanceId.value,
          taskId: taskId.value
        }).finally(() => {});
        MciNotification.success(i18n.t('加签成功'));
        await getApprovalProgress();
        emit('close');
      };
      return MciMessageBox.confirm(i18n.t('确定增加并行审批人员吗？'), i18n.t('提示'), {
        requestLoading() {
          return submitHandle();
        }
      });
    };
    // 已经添加的用户不在列表中
    const filterUser = (list: IOption[]) => {
      return list.filter((item) => {
        return !props.excludeId.includes(Number(item.value));
      });
    };
    const formConfig = ref<IVitalFormConfig<IPostWorkflowApprovalTaskAddReq>>({
      attrs: {},
      layout: {
        cols: 1
      },
      initModel: {
        userIds: []
      },
      formItems: [
        {
          attrs: {},
          rulePresets: {
            rules: [{ rule: 'required', trigger: 'change', prefixMsg: i18n.t('请选择加签人') }]
          },
          fields: [
            {
              prop: 'userIds',
              type: 'investUserSelector',
              attrs: {
                multiple: true,
                filterList: filterUser,
                style: {
                  width: '100%'
                }
              }
            }
          ]
        }
      ]
    });
    return {
      formConfig,
      formRef,
      confirmHandle,
      filterUser
    };
  },
  render() {
    return (
      <MciDialog
        width="480px"
        title={i18n.t('加签')}
        cancelText={i18n.t('取消')}
        isConfirmClose={false}
        confirmText={i18n.t('确定')}
        destroy-on-close
        confirmHandle={this.confirmHandle}>
        <VitalForm ref="formRef" config={this.formConfig} />
      </MciDialog>
    );
  }
});
